package com.zhiwen.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiwen.common.exception.BusinessException;
import com.zhiwen.domain.dto.QuestionDTO;
import com.zhiwen.domain.entity.*;
import com.zhiwen.mapper.QuestionMapper;
import com.zhiwen.mapper.UserCollectionMapper;
import com.zhiwen.mapper.UserLikeMapper;
import com.zhiwen.service.CategoryService;
import com.zhiwen.service.QuestionService;
import com.zhiwen.service.UserFollowService;
import com.zhiwen.service.UserService;
import com.zhiwen.domain.vo.QuestionVO;
import com.zhiwen.domain.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 问题服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    private final UserService userService;
    private final CategoryService categoryService;
    private final UserFollowService userFollowService;

    // 添加必要的Mapper依赖
    private final UserLikeMapper userLikeMapper;
    private final UserCollectionMapper userCollectionMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public QuestionVO createQuestion(QuestionDTO questionDTO) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 创建问题
        Question question = new Question();
        BeanUtils.copyProperties(questionDTO, question);

        // 设置问题初始值
        question.setUserId(userId);
        question.setStatus(0); // 待审核
        question.setViewCount(0);
        question.setAnswerCount(0);
        question.setFavoriteCount(0);
        question.setCreateTime(LocalDateTime.now());
        question.setUpdateTime(LocalDateTime.now());

        // 保存问题
        save(question);

        return convertToVO(question);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QuestionVO updateQuestion(QuestionDTO questionDTO) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 查询问题
        Question question = getById(questionDTO.getId());
        if (question == null) {
            throw new BusinessException("问题不存在");
        }

        // 检查权限（只有管理员或问题创建者可以修改）
        User user = userService.getById(userId);
        if (!userId.equals(question.getUserId()) && user.getRole() != 3) {
            throw new BusinessException("无权限修改该问题");
        }

        // 更新问题
        BeanUtils.copyProperties(questionDTO, question);
        question.setUpdateTime(LocalDateTime.now());

        // 保存问题
        updateById(question);

        return convertToVO(question);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQuestion(Long id) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 查询问题
        Question question = getById(id);
        if (question == null) {
            throw new BusinessException("问题不存在");
        }

        // 检查权限（只有管理员或问题创建者可以删除）
        User user = userService.getById(userId);
        if (!userId.equals(question.getUserId()) && user.getRole() != 3) {
            throw new BusinessException("无权限删除该问题");
        }

        // 删除问题（逻辑删除）
        removeById(id);
    }

    @Override
    public QuestionVO getQuestionDetail(Long id) {
        // 查询问题
        Question question = getById(id);
        if (question == null || question.getDeleted() == 1) {
            throw new BusinessException("问题不存在");
        }

        return convertToVO(question);
    }

    @Override
    public Page<QuestionVO> getQuestionPage(Long categoryId, String keyword, Integer status, Page<Question> page) {
        // 构建查询条件
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 分类条件
        if (categoryId != null) {
            wrapper.eq(Question::getCategoryId, categoryId);
        }

        // 关键词搜索
        if (StrUtil.isNotBlank(keyword)) {
            wrapper.and(w -> w.like(Question::getTitle, keyword).or().like(Question::getContent, keyword));
        }

        // 状态条件
        if (status != null) {
            wrapper.eq(Question::getStatus, status);
        } else {
            // 默认查询已发布和已解决的问题
            wrapper.in(Question::getStatus, 1, 2);
        }

        // 已删除条件
        wrapper.eq(Question::getDeleted, 0);

        // 排序
        wrapper.orderByDesc(Question::getCreateTime);

        // 分页查询
        Page<Question> questionPage = page(page, wrapper);

        // 转换结果
        List<QuestionVO> questionVOList = questionPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());

        // 构建返回结果
        Page<QuestionVO> questionVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionVOPage, "records");
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    @Override
    public void incrementViewCount(Long id) {
        // 查询问题
        Question question = getById(id);
        if (question != null) {
            // 增加浏览量
            question.setViewCount(question.getViewCount() + 1);
            updateById(question);
        }
    }

    @Override
    public void updateQuestionStatus(Long id, Integer status) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 查询问题
        Question question = getById(id);
        if (question == null) {
            throw new BusinessException("问题不存在");
        }

        // 检查权限（只有管理员或问题创建者可以修改状态）
        User user = userService.getById(userId);
        if (!userId.equals(question.getUserId()) && user.getRole() != 3) {
            throw new BusinessException("无权限修改该问题状态");
        }

        // 更新状态
        question.setStatus(status);
        question.setUpdateTime(LocalDateTime.now());
        updateById(question);
    }

    @Override
    public Page<QuestionVO> getHotQuestions(Page<Question> page) {
        // 构建查询条件
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 已发布和已解决的问题
        wrapper.in(Question::getStatus, 1, 2);

        // 未删除
        wrapper.eq(Question::getDeleted, 0);

        // 按照浏览量排序
        wrapper.orderByDesc(Question::getViewCount);

        // 分页查询
        Page<Question> questionPage = page(page, wrapper);

        // 转换结果
        List<QuestionVO> questionVOList = questionPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());

        // 构建返回结果
        Page<QuestionVO> questionVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionVOPage, "records");
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    @Override
    public Page<QuestionVO> getWaitingQuestions(Page<Question> page) {
        // 构建查询条件
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 已发布的问题
        wrapper.eq(Question::getStatus, 1);

        // 未删除
        wrapper.eq(Question::getDeleted, 0);

        // 没有回答或回答少的优先
        wrapper.orderByAsc(Question::getAnswerCount);
        wrapper.orderByDesc(Question::getCreateTime);

        // 分页查询
        Page<Question> questionPage = page(page, wrapper);

        // 转换结果
        List<QuestionVO> questionVOList = questionPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());

        // 构建返回结果
        Page<QuestionVO> questionVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionVOPage, "records");
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    @Override
    public Page<QuestionVO> getUserQuestions(Long userId, Page<Question> page) {
        // 构建查询条件
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 用户条件
        wrapper.eq(Question::getUserId, userId);

        // 未删除
        wrapper.eq(Question::getDeleted, 0);

        // 按创建时间倒序
        wrapper.orderByDesc(Question::getCreateTime);

        // 分页查询
        Page<Question> questionPage = page(page, wrapper);

        // 转换结果
        List<QuestionVO> questionVOList = questionPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());

        // 构建返回结果
        Page<QuestionVO> questionVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionVOPage, "records");
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    @Override
    public Page<QuestionVO> getQuestionPage(Page<Question> page, LambdaQueryWrapper<Question> wrapper) {
        // 分页查询
        Page<Question> questionPage = page(page, wrapper);

        // 转换结果
        List<QuestionVO> questionVOList = questionPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());

        // 构建返回结果
        Page<QuestionVO> questionVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionVOPage, "records");
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    @Override
    public Page<QuestionVO> getRecommendQuestions(Page<Question> page) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();

        // 构建查询条件
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 已发布和已解决的问题
        wrapper.in(Question::getStatus, 1, 2);

        // 未删除
        wrapper.eq(Question::getDeleted, 0);

        try {
            // 推荐问题列表
            List<Question> recommendQuestions = new ArrayList<>();

            // 1. 协同过滤推荐（基于用户行为）
            List<Long> cfRecommendIds = getCollaborativeFilteringRecommendations(userId);

            // 2. 获取用户关注的用户列表
            List<Long> followingUserIds = userFollowService.getFollowingUserIds(userId);

            // 3. 获取用户偏好分类
            Long preferredCategoryId = getPreferredCategory(userId);

            if (!cfRecommendIds.isEmpty()) {
                // 如果有协同过滤推荐结果，优先使用
                wrapper.and(w -> {
                    // 协同过滤推荐的问题
                    w.in(Question::getId, cfRecommendIds);

                    // 或者关注用户的问题（如果有关注用户）
                    if (!followingUserIds.isEmpty()) {
                        w.or().in(Question::getUserId, followingUserIds);
                    }

                    // 或者用户偏好分类的问题（如果有偏好分类）
                    if (preferredCategoryId != null) {
                        w.or().eq(Question::getCategoryId, preferredCategoryId);
                    }

                    // 或者热门问题
                    w.or().gt(Question::getViewCount, 100);

                    // 或者近期问题
                    w.or().gt(Question::getCreateTime, LocalDateTime.now().minusDays(7));
                });

                // 按协同过滤推荐顺序排序（使用FIELD函数）
                wrapper.last("ORDER BY FIELD(id," + cfRecommendIds.stream().map(String::valueOf).collect(Collectors.joining(",")) + ") DESC, view_count DESC, create_time DESC");
            } else if (!followingUserIds.isEmpty()) {
                // 用户有关注的人，优先推荐关注用户的问题
                wrapper.and(w -> {
                    // 关注用户的问题
                    w.in(Question::getUserId, followingUserIds);

                    // 或者用户偏好分类的问题（如果有偏好分类）
                    if (preferredCategoryId != null) {
                        w.or().eq(Question::getCategoryId, preferredCategoryId);
                    }

                    // 或者热门问题
                    w.or().gt(Question::getViewCount, 100);

                    // 或者近期问题
                    w.or().gt(Question::getCreateTime, LocalDateTime.now().minusDays(7));
                });

                // 排序：先按关注用户分组，再按热度和时间排序
                wrapper.orderByDesc(Question::getViewCount);
                wrapper.orderByDesc(Question::getCreateTime);
            } else {
                // 冷启动情况：用户没有关注的人且没有行为数据
                if (preferredCategoryId != null) {
                    // 如果有偏好分类，优先推荐该分类的问题
                    wrapper.and(w -> {
                        w.eq(Question::getCategoryId, preferredCategoryId);
                        w.or().gt(Question::getViewCount, 50);
                        w.or().gt(Question::getCreateTime, LocalDateTime.now().minusDays(14));
                    });
                } else {
                    // 完全冷启动，按照热度和时间排序
                    wrapper.orderByDesc(Question::getViewCount);
                    wrapper.orderByDesc(Question::getCreateTime);
                }
            }

            // 排除用户自己的问题
            wrapper.ne(Question::getUserId, userId);

        } catch (Exception e) {
            log.error("推荐系统异常，降级为热门推荐", e);
            // 如果推荐算法失败，降级为热门和时间排序
            wrapper.orderByDesc(Question::getViewCount);
            wrapper.orderByDesc(Question::getCreateTime);
        }

        // 分页查询
        Page<Question> questionPage = page(page, wrapper);

        // 转换结果
        List<QuestionVO> questionVOList = questionPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());

        // 构建返回结果
        Page<QuestionVO> questionVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionVOPage, "records");
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    /**
     * 基于协同过滤算法获取推荐问题ID列表
     *
     * @param userId 用户ID
     * @return 推荐问题ID列表
     */
    private List<Long> getCollaborativeFilteringRecommendations(Long userId) {
        try {
            // 推荐缓存key
            String cacheKey = "user:cf_recommend:" + userId;

            // 1. 先从Redis缓存获取
            @SuppressWarnings("unchecked") List<Long> cachedRecommendations = (List<Long>) redisTemplate.opsForValue().get(cacheKey);
            if (cachedRecommendations != null && !cachedRecommendations.isEmpty()) {
                return cachedRecommendations;
            }

            // 2. 缓存未命中，计算推荐结果
            List<Long> recommendations = new ArrayList<>();

            // 2.1 获取用户的行为数据
            Map<Long, Double> userBehaviors = getUserBehaviors(userId);
            if (userBehaviors.isEmpty()) {
                return recommendations; // 无行为数据则返回空列表
            }

            // 2.2 找到相似用户
            List<Long> similarUserIds = findSimilarUsers(userId, userBehaviors);
            if (similarUserIds.isEmpty()) {
                return recommendations; // 无相似用户则返回空列表
            }

            // 2.3 获取相似用户行为过的问题
            Set<Long> viewedQuestionIds = userBehaviors.keySet();
            List<Long> candidateQuestions = getQuestionsByUserIds(similarUserIds, viewedQuestionIds);
            if (candidateQuestions.isEmpty()) {
                return recommendations; // 无候选问题则返回空列表
            }

            // 2.4 按相似度排序候选问题
            Map<Long, Double> questionScores = calculateQuestionScores(candidateQuestions, similarUserIds, userId);

            // 2.5 转换为有序列表

            recommendations = questionScores.entrySet().stream().sorted(Map.Entry.<Long, Double>comparingByValue().reversed()).map(Map.Entry::getKey).limit(20) // 最多取20条推荐
                    .collect(Collectors.toList());

            // 3. 缓存推荐结果（1小时）
            if (!recommendations.isEmpty()) {
                redisTemplate.opsForValue().set(cacheKey, recommendations, 1, TimeUnit.HOURS);
            }

            return recommendations;
        } catch (Exception e) {
            log.error("协同过滤推荐计算异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 计算候选问题的推荐得分
     */
    private Map<Long, Double> calculateQuestionScores(List<Long> candidateQuestions, List<Long> similarUserIds, Long userId) {
        Map<Long, Double> questionScores = new HashMap<>();

        if (candidateQuestions.isEmpty() || similarUserIds.isEmpty()) {
            return questionScores;
        }

        try {
            // 1. 对每个候选问题，计算综合得分
            for (Long questionId : candidateQuestions) {
                double score = 0.0;

                // 1.1 计算用户行为匹配得分 - 使用正确的mapper
                QueryWrapper<UserLike> likeCountWrapper = new QueryWrapper<>();
                likeCountWrapper.eq("target_id", questionId).eq("target_type", 1).in("user_id", similarUserIds).eq("deleted", 0);

                Long likeCount = userLikeMapper.selectCount(likeCountWrapper);
                score += likeCount * 2.0;

                // 1.2 收藏行为得分 - 使用正确的mapper
                QueryWrapper<UserCollection> collectCountWrapper = new QueryWrapper<>();
                collectCountWrapper.eq("target_id", questionId).eq("type", 1).in("user_id", similarUserIds).eq("deleted", 0);

                Long collectCount = userCollectionMapper.selectCount(collectCountWrapper);
                score += collectCount * 3.0;

                // 1.3 获取问题信息 - 使用单独查询对象避免类型转换问题
                Question question = baseMapper.selectById(questionId);

                if (question != null) {
                    // 浏览量加分
                    Integer viewCount = question.getViewCount();
                    if (viewCount != null) {
                        score += Math.min(viewCount / 100.0, 5.0);
                    }

                    // 回答数加分
                    Integer answerCount = question.getAnswerCount();
                    if (answerCount != null) {
                        score += Math.min(answerCount * 0.5, 5.0);
                    }

                    // 时间衰减因子（近期内容得分更高）
                    LocalDateTime createTime = question.getCreateTime();
                    if (createTime != null) {
                        long daysBetween = ChronoUnit.DAYS.between(createTime, LocalDateTime.now());
                        double timeFactor = Math.exp(-0.05 * daysBetween); // 指数衰减
                        score *= timeFactor;
                    }

                    // 如果问题分类是用户偏好分类，加分
                    Long preferredCategoryId = getPreferredCategory(userId);
                    Long categoryId = question.getCategoryId();
                    if (preferredCategoryId != null && categoryId != null && preferredCategoryId.equals(categoryId)) {
                        score *= 1.5; // 偏好分类加成50%
                    }
                }

                // 保存计算结果
                questionScores.put(questionId, score);
            }
        } catch (Exception e) {
            log.error("计算问题推荐得分异常", e);
        }

        return questionScores;
    }

    /**
     * 获取用户偏好的分类
     *
     * @param userId 用户ID
     * @return 偏好分类ID或null
     */
    private Long getPreferredCategory(Long userId) {
        try {
            // 这里需要使用原生SQL，因为MyBatisPlus不直接支持复杂的分组和聚合
            String sql = "SELECT category_id FROM question WHERE user_id = " + userId + " AND deleted = 0 AND category_id IS NOT NULL " + "GROUP BY category_id ORDER BY COUNT(*) DESC LIMIT 1";

            QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
            queryWrapper.apply(sql);

            List<Object> objs = baseMapper.selectObjs(queryWrapper);

            if (objs != null && !objs.isEmpty() && objs.get(0) != null) {
                if (objs.get(0) instanceof Number) {
                    return ((Number) objs.get(0)).longValue();
                }
            }
            return null;
        } catch (Exception e) {
            log.error("获取用户偏好分类失败", e);
            return null;
        }
    }

    /**
     * 获取用户的行为数据（问题ID -> 行为权重）
     */
    private Map<Long, Double> getUserBehaviors(Long userId) {
        Map<Long, Double> userBehaviors = new HashMap<>();

        try {
            // 1. 获取用户浏览过的问题（权重1.0）
            LambdaQueryWrapper<Question> viewWrapper = new LambdaQueryWrapper<>();
            viewWrapper.select(Question::getId);
            viewWrapper.eq(Question::getUserId, userId);
            viewWrapper.eq(Question::getDeleted, 0);
            List<Question> viewedQuestions = baseMapper.selectList(viewWrapper);
            for (Question question : viewedQuestions) {
                userBehaviors.put(question.getId(), 1.0);
            }

            // 2. 获取用户点赞的问题（权重2.0）
            QueryWrapper<UserLike> likeWrapper = new QueryWrapper<>();
            likeWrapper.select("target_id").eq("user_id", userId).eq("target_type", 1) // 1-问题
                    .eq("deleted", 0);

            List<Object> likedQuestionObjs = userLikeMapper.selectObjs(likeWrapper);

            for (Object obj : likedQuestionObjs) {
                if (obj instanceof Number) {
                    Long questionId = ((Number) obj).longValue();
                    userBehaviors.put(questionId, 2.0); // 点赞权重更高
                }
            }

            // 3. 获取用户收藏的问题（权重3.0）
            QueryWrapper<UserCollection> collectWrapper = new QueryWrapper<>();
            collectWrapper.select("target_id").eq("user_id", userId).eq("type", 1).eq("deleted", 0);

            List<Object> collectedQuestionObjs = userCollectionMapper.selectObjs(collectWrapper);

            for (Object obj : collectedQuestionObjs) {
                if (obj instanceof Number) {
                    Long questionId = ((Number) obj).longValue();
                    userBehaviors.put(questionId, 3.0); // 收藏权重最高
                }
            }
        } catch (Exception e) {
            log.error("获取用户行为数据异常", e);
        }

        return userBehaviors;
    }

    /**
     * 找到与当前用户相似的用户
     */
    private List<Long> findSimilarUsers(Long userId, Map<Long, Double> userBehaviors) {
        try {
            // 1. 获取有过互动的问题ID列表
            List<Long> interactedQuestionIds = new ArrayList<>(userBehaviors.keySet());
            if (interactedQuestionIds.isEmpty()) {
                return Collections.emptyList();
            }

            // 2. 找到对这些问题有过互动的其他用户 - 使用正确的mapper
            QueryWrapper<UserLike> likeUserWrapper = new QueryWrapper<>();
            likeUserWrapper.select("DISTINCT user_id").eq("target_type", 1).in("target_id", interactedQuestionIds).ne("user_id", userId).eq("deleted", 0).last("LIMIT 50");

            List<Object> likeUserObjs = userLikeMapper.selectObjs(likeUserWrapper);

            List<Long> similarUserIds = new ArrayList<>();
            for (Object obj : likeUserObjs) {
                if (obj instanceof Number) {
                    similarUserIds.add(((Number) obj).longValue());
                }
            }

            // 3. 添加收藏过相同问题的用户 - 使用正确的mapper
            QueryWrapper<UserCollection> collectUserWrapper = new QueryWrapper<>();
            collectUserWrapper.select("DISTINCT user_id").eq("type", 1).in("target_id", interactedQuestionIds).ne("user_id", userId).eq("deleted", 0).last("LIMIT 50");

            List<Object> collectUserObjs = userCollectionMapper.selectObjs(collectUserWrapper);

            for (Object obj : collectUserObjs) {
                if (obj instanceof Number) {
                    Long similarUserId = ((Number) obj).longValue();
                    if (!similarUserIds.contains(similarUserId)) {
                        similarUserIds.add(similarUserId);
                    }
                }
            }

            return similarUserIds;
        } catch (Exception e) {
            log.error("查找相似用户异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 获取指定用户群体互动过的问题ID列表（排除当前用户已互动的）
     */
    private List<Long> getQuestionsByUserIds(List<Long> userIds, Set<Long> excludeQuestionIds) {
        if (userIds.isEmpty()) {
            return Collections.emptyList();
        }

        try {
            List<Long> candidateQuestions = new ArrayList<>();

            // 1. 获取用户点赞的问题 - 使用正确的mapper
            QueryWrapper<UserLike> likeQueryWrapper = new QueryWrapper<>();
            likeQueryWrapper.select("DISTINCT target_id").eq("target_type", 1).in("user_id", userIds).eq("deleted", 0).last("LIMIT 100");

            List<Object> likedQuestionObjs = userLikeMapper.selectObjs(likeQueryWrapper);

            for (Object obj : likedQuestionObjs) {
                if (obj instanceof Number) {
                    Long questionId = ((Number) obj).longValue();
                    if (!excludeQuestionIds.contains(questionId)) {
                        candidateQuestions.add(questionId);
                    }
                }
            }

            // 2. 获取用户收藏的问题 - 使用正确的mapper
            QueryWrapper<UserCollection> collectQueryWrapper = new QueryWrapper<>();
            collectQueryWrapper.select("DISTINCT target_id").eq("type", 1).in("user_id", userIds).eq("deleted", 0).last("LIMIT 100");

            List<Object> collectedQuestionObjs = userCollectionMapper.selectObjs(collectQueryWrapper);

            for (Object obj : collectedQuestionObjs) {
                if (obj instanceof Number) {
                    Long questionId = ((Number) obj).longValue();
                    if (!excludeQuestionIds.contains(questionId) && !candidateQuestions.contains(questionId)) {
                        candidateQuestions.add(questionId);
                    }
                }
            }

            // 3. 检查这些问题的状态 - 使用已有的mapper
            if (!candidateQuestions.isEmpty()) {
                // 使用LambdaQueryWrapper更加类型安全
                LambdaQueryWrapper<Question> questionQueryWrapper = new LambdaQueryWrapper<>();
                questionQueryWrapper.select(Question::getId);
                questionQueryWrapper.in(Question::getId, candidateQuestions);
                questionQueryWrapper.in(Question::getStatus, Arrays.asList(1, 2));
                questionQueryWrapper.eq(Question::getDeleted, 0);

                List<Question> validQuestions = baseMapper.selectList(questionQueryWrapper);

                List<Long> validQuestionIds = validQuestions.stream().map(Question::getId).collect(Collectors.toList());

                return validQuestionIds;
            }

            return candidateQuestions;
        } catch (Exception e) {
            log.error("获取候选问题异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    public Page<QuestionVO> getFollowingUserQuestions(Page<Question> page) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 先获取用户关注的用户ID列表
        List<Long> followingUserIds = userFollowService.getFollowingUserIds(userId);

        // 如果没有关注任何用户，返回空数据
        if (followingUserIds.isEmpty()) {
            return new Page<>();
        }

        // 构建查询条件
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 只查询关注用户的问题
        wrapper.in(Question::getUserId, followingUserIds);

        // 已发布和已解决的问题
        wrapper.in(Question::getStatus, 1, 2);

        // 未删除
        wrapper.eq(Question::getDeleted, 0);

        // 按创建时间排序
        wrapper.orderByDesc(Question::getCreateTime);

        // 分页查询
        Page<Question> questionPage = page(page, wrapper);

        // 转换结果
        List<QuestionVO> questionVOList = questionPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());

        // 构建返回结果
        Page<QuestionVO> questionVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionVOPage, "records");
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    /**
     * 转换为VO对象
     */
    private QuestionVO convertToVO(Question question) {
        QuestionVO questionVO = new QuestionVO();
        BeanUtils.copyProperties(question, questionVO);

        // 设置用户信息
        User user = userService.getById(question.getUserId());
        if (user != null) {
            questionVO.setNickname(user.getNickname());
            questionVO.setAvatar(user.getAvatar());
            questionVO.setUsername(user.getUsername());
            questionVO.setIsExpert(user.getRole() == 2);

            // 添加完整的用户信息
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            questionVO.setUser(userVO);
        }

        // 设置分类名称
        if (question.getCategoryId() != null) {
            Category category = categoryService.getById(question.getCategoryId());
            String name = category.getName();
            questionVO.setCategoryName(name);
        }

        return questionVO;
    }
}
